package hangler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"horizon-ai/cache"
	"horizon-ai/models"
	"strconv"
	"time"
)

func Class(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var list models.ListClass
	/*SELECT
	  good_classes.cla_id AS GlsId,
	  classes.`name` AS NAME,
	  classes.num AS Num,
	  good_classes.order_class AS OrderClass,
	  good_classes.str_class AS StrClass
	FROM
	  classes
	  LEFT JOIN good_classes ON classes.id = good_classes.cla_id
	*/
	res_key := "class" + strconv.Itoa(page)
	result, _ := cache.Rdb.Get(cache.Ctx, res_key).Result()
	if result == "" {

		models.DB.Table("good_class").
			Select("good_classes.cla_id AS GlsId",
				"classes.`name` AS NAME",
				"classes.num AS Num",
				" good_classes.order_class AS OrderClass",
				" good_classes.str_class AS StrClass",
			).
			Joins("  LEFT JOIN good_classes ON classes.id = good_classes.cla_id").
			Offset(offset).Limit(size).Debug().Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, res_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &list)
	}
	var total int64
	models.DB.Model(&models.GoodClass{}).Count(&total)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"total": total,
			"list":  list,
		},
	})
	return

}
